import { getData } from '@/service/getData';
import store from '@/store/index';

// 获取高度
const getEleNum = (eles, nums, type = '-') => {
  let getEleNum = document.getElementsByClassName(eles) || document.getElementById(eles);
  let eleHeight = getEleNum[0] ? getEleNum[0].clientHeight : getEleNum.clientHeight;
  if (!eleHeight) return '0px';
  let resultNum = 0;
  if (type == '-') {
    resultNum = eleHeight - nums / 1;
  } else if (type == '+') {
    resultNum = eleHeight + nums / 1;
  }
  return resultNum;
};
export { getEleNum };

/**
 * 时间戳转日期
 * @param stamp
 * @param type 1. yyyy-mm-dd  2.yyyy-mm-dd h:minute:second
 * @returns {string}
 */
export const formatDate = (stamp, type = 2) => {
  if (!stamp) {
    return '';
  }
  function format(par) {
    return par < 10 ? '0' + par : par;
  }
  var str = '';
  let date = new Date(stamp);
  var year = date.getFullYear();
  var month = format(date.getMonth() + 1);
  var day = format(date.getDate());
  var hours = format(date.getHours());
  var minutes = format(date.getMinutes());
  var seconds = format(date.getSeconds());
  if (type == 1) {
    // 2008-01-01
    str = year + '-' + month + '-' + day;
  } else if (type == 2) {
    // 2008-01-01 09:20:20
    str = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  } else if (type == 3) {
    // 09:20:20
    str = hours + ':' + minutes + ':' + seconds;
  } else if (type == 4) {
    // 1999-02-01 15时
    str = year + '-' + month + '-' + day + ' ' + hours + '时';
  } else if (type == 5) {
    // 2008年01月01日 09时20分20秒
    str = year + '年' + month + '月' + day + '日 ' + hours + '时' + minutes + '分' + seconds + '秒';
  }
  return str;
};
export const formatDateCn = (stamp) => {
  function format(par) {
    return par < 10 ? '0' + par : par;
  }
  var str = '';
  let date = new Date(stamp);
  var year = date.getFullYear();
  var month = format(date.getMonth() + 1);
  var day = format(date.getDate());
  var hours = format(date.getHours());
  var minutes = format(date.getMinutes());
  var seconds = format(date.getSeconds());
  str = year + '年' + month + '月' + day + '日';

  return str;
};
/**
 * 获取当前系统时间前几个小时的日期
 * @param lastStamp 需要减去的时间戳
 * @param type 1. yyyy-mm-dd  2.yyyy-mm-dd h:minute:second
 * @returns {string}
 */
export const lastHourTime = (lastStamp, type = 1) => {
  function format(par) {
    return par < 10 ? '0' + par : par;
  }
  var str = '';
  let newLastStamp = lastStamp || 0; // 默认前1小时
  var myDate = new Date();
  var yesterday = new Date(myDate.getTime() - newLastStamp);
  var year = yesterday.getFullYear();
  var month = format(yesterday.getMonth() + 1);
  var day = format(yesterday.getDate());
  var hours = format(yesterday.getHours());
  var minutes = format(yesterday.getMinutes());
  var seconds = format(yesterday.getSeconds());
  if (type == 1) {
    str = year + '-' + month + '-' + day;
  } else {
    str = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  }
  return str;
};

/**
 * 日期转时间戳
 * @param date 传入的日期格式
 * @returns {string}
 */
export const getTimeStamp = (date) => {
  var str = '';
  if (date !== '') {
    str = Date.parse(new Date(date));
  }
  return str;
};

/**
 * 深拷贝
 * @param 对象
 * @returns {Object}
 */

export const deepClone = (obj, hash = new WeakMap()) => {
  function isObject(value) {
    const type = typeof value;
    return value != null && (type == 'object' || type == 'function');
  }
  if (null == obj || 'object' != typeof obj) return obj;
  let cloneObj;
  let Constructor = obj.constructor;
  // console.log(1, Constructor)
  switch (Constructor) {
    case RegExp:
      cloneObj = new Constructor(obj);
      break;
    case Date:
      cloneObj = new Constructor(obj.getTime());
      break;
    default:
      if (hash.has(obj)) return hash.get(obj);
      cloneObj = new Constructor();
      hash.set(obj, cloneObj);
    // console.log(2, hash.get(obj))
  }
  for (let key in obj) {
    // console.log(3, key, cloneObj)
    cloneObj[key] = isObject(obj[key]) ? deepClone(obj[key], hash) : obj[key];
    // console.log(4, key, cloneObj[key])
  }
  return cloneObj;
};

export const deepObjectMerge = (FirstOBJ, SecondOBJ) => {
  // 深度合并对象
  for (var key in SecondOBJ) {
    FirstOBJ[key] =
      FirstOBJ[key] && FirstOBJ[key].toString().indexOf('[object Object]') > -1
        ? deepObjectMerge(FirstOBJ[key], SecondOBJ[key])
        : (FirstOBJ[key] = SecondOBJ[key]);
  }
  return FirstOBJ;
};

/**
 * 数组内对象转数组
 * @param arr
 * @returns {Array}
 */
export const transFormObjectToArr = (arr) => {
  if (!arr) {
    return [];
  }
  let _arr = [];
  for (let i = 0; i < arr.length; i++) {
    _arr.push([i - 0, arr[i].value - 0]);
  }
  return _arr;
};
/**
 * 求标准差
 */
export const standardDeviation = (arr) => {
  let _arr = [];
  for (let i = 0; i < arr.length; i++) {
    _arr.push(arr[i].value);
  }
  let sum = function (x, y) {
    return x + y;
  }; //求和函数
  let square = function (x) {
    return x * x;
  }; //数组中每个元素求它的平方
  let mean = _arr.reduce(sum) / _arr.length;
  let deviations = _arr.map(function (x) {
    return x - mean;
  });
  let stddev = Math.sqrt(deviations.map(square).reduce(sum) / (_arr.length - 1));
  return stddev;
};

/**
 **
 * 将svg导出成图片
 * @param node svg节点 => document.querySelector('svg')
 * @param name 生成的图片名称
 * @param width 生成的图片宽度
 * @param height 生成的图片高度
 * @param type 生成的图片类型
 */
export const covertSVG2Image = (node, name, width, height, type = 'png') => {
  let serializer = new XMLSerializer();
  let source = '<?xml version="1.0" standalone="no"?>\r\n' + serializer.serializeToString(node);
  let image = new Image();
  image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source);
  let canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  let context = canvas.getContext('2d');
  context.fillStyle = '#1E212C';
  context.fillRect(0, 0, 10000, 10000);
  image.onload = function () {
    context.drawImage(image, 0, 0);
    let a = document.createElement('a');
    a.download = `${name}.${type}`;
    a.href = canvas.toDataURL(`image/${type}`, 1.0);
    a.click();
  };
};

/**
 * js脚本实现页面一位数字显示为两位，不足两位前面加“0”
 * @param num 传入的数字
 * @param length 显示为几位数
 * @returns {string}
 */
export const fix = (num, length) => {
  return ('' + num).length < length
    ? (new Array(length + 1).join('0') + num).slice(-length)
    : '' + num;
};

/**
 * js脚本实现echart图转换为图片下载
 * @param char 传入的id
 * @param title 图片的标题
 * @returns {string}
 */
export const downImg = (char, title) => {
  setTimeout(function () {
    let img = new Image();
    img.src = char.getDataURL({
      pixelRatio: 2,
      type: 'png',
      backgroundColor: '#00001E',
    });
    img.onload = function () {
      var canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      var dataURL = canvas.toDataURL('image/png');
      var a = document.createElement('a');
      // 创建一个单击事件
      var event = new MouseEvent('click');
      // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
      a.download = title;
      // 将生成的URL设置为a.href属性
      a.href = dataURL;
      // 触发a的单击事件
      a.dispatchEvent(event);
    };
    /**请求后端接口****提供操作记录 ****************************************************/
    store.commit('SAVE_OPERATE', title + '图片下载');
  }, 1000);
};
/**
 * 当天往前推7天的时间戳
 */
export const getLast7DayTime = () => {
  // 当天23：59:59
  let time1 = new Date(
    new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1,
  );
  // 7天前
  let time2 = new Date(
    new Date(new Date().toLocaleDateString()).getTime() - 6 * 24 * 60 * 60 * 1000,
  );
  return [time2, time1];
};

/**
 * 获取两个时间的间隔时间
 * @param 两个时间戳
 */
export function getTimeDiffrence(date1, date2) {
  let diff = '';

  const dateBegin = new Date(date1);
  const dateEnd = new Date(date2);

  if (dateBegin >= dateEnd) {
    diff = '-';
  } else {
    const dateDiff = dateEnd.getTime() - dateBegin.getTime();
    const dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
    const leave1 = dateDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    const hours = Math.floor(leave1 / (3600 * 1000)); //计算出小时数
    const leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    const minutes = Math.floor(leave2 / (60 * 1000)); //计算相差分钟数
    const leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    const seconds = Math.round(leave3 / 1000);

    diff += dayDiff > 0 ? dayDiff + ' 天 ' : '';
    diff += hours > 0 ? hours + ' 小时 ' : '';
    diff += minutes > 0 ? minutes + ' 分钟 ' : '';
    diff += seconds > 0 ? seconds + ' 秒' : '';
  }

  return diff;
}

/**
 * 获取两个时间的间隔时间
 * @param 时间秒数
 */
export function getTimeDiffrence2(num0) {
  let num = num0;
  let diff = '';

  if (!num) {
    if (num == 0) {
      diff = '0 秒';
    } else {
      diff = '--';
    }
  } else {
    const dateDiff = num * 1000; // 转成毫秒
    const dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
    const leave1 = dateDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    const hours = Math.floor(leave1 / (3600 * 1000)); //计算出小时数
    const leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    const minutes = Math.floor(leave2 / (60 * 1000)); //计算相差分钟数
    const leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    const seconds = Math.round(leave3 / 1000);

    diff += dayDiff > 0 ? dayDiff + ' 天 ' : '';
    diff += hours > 0 ? hours + ' 小时 ' : '';
    diff += minutes > 0 ? minutes + ' 分钟 ' : '';
    diff += seconds > 0 ? seconds + ' 秒' : '';
  }

  return diff;
}

/**
 * 生成颜色数组,用于生成图表颜色
 * @param {*} arrLength 需要的颜色数组长度
 * @returns
 */
export function generatorColorArr(arrLength) {
  const colorTypes = [
    '#6236FF',
    '#2E78FF',
    '#32C5FF',
    '#44D7B6',
    '#39796b',
    '#dd3131',
    '#EBB00E',
    '#DF6400',
    '#DA4992',
    '#2196F3',
    '#ff5f52',
    '#3f51b5',
  ];

  let colorArr = new Array(arrLength).fill(null);
  colorArr.forEach((color, index) => {
    if (colorTypes[index]) {
      colorArr[index] = colorTypes[index];
    } else {
      colorArr[index] = colorTypes[index - colorTypes.length];
    }
  });

  return colorArr;
}

//阿拉伯数字转中文数字
export function NoToChinese(num) {
  console.log(num);
  if (!/^\d*(\.\d*)?$/.test(num)) {
    alert('Number is wrong!');
    return 'Number is wrong!';
  }
  var AA = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
  var BB = new Array('', '十', '百', '千', '万', '亿', '点', '');
  var a = ('' + num).replace(/(^0*)/g, '').split('.'),
    k = 0,
    re = '';
  for (var i = a[0].length - 1; i >= 0; i--) {
    switch (k) {
      case 0:
        re = BB[7] + re;
        break;
      case 4:
        if (!new RegExp('0{4}\\d{' + (a[0].length - i - 1) + '}$').test(a[0])) re = BB[4] + re;
        break;
      case 8:
        re = BB[5] + re;
        BB[7] = BB[5];
        k = 0;
        break;
    }
    if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
    if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
    k++;
  }
  if (a.length > 1) {
    //加上小数部分(如果有小数部分)
    re += BB[6];
    for (var j = 0; j < a[1].length; j++) re += AA[a[1].charAt(j)];
  }
  return re;
}

/**
 *  毫秒时间戳转成秒时间戳
 */
export function msToS(stamp) {
  if (stamp) {
    if (('' + stamp).length > 10) {
      return parseFloat((stamp / 1000).toFixed(0));
    } else {
      return stamp;
    }
  }
  return '';
}

/**
 * 语音朗读方法
 */
export function readMsg(text) {
  if (text) {
    const repeatNum = 3;
    // debugger
    // window.speechSynthesis.cancel();
    var msg = new SpeechSynthesisUtterance();
    msg.text = text;

    // 增加控制播放次数
    let count = 0;
    // speechSynthesis.speak(msg);
    while (count < repeatNum) {
      console.log(text);
      speechSynthesis.speak(msg);
      count++;
    }
    // window.speechSynthesis.speak(msg);
  } else {
    console.log('朗读正在被占用');
  }
}

/**
 * // 正则分离出板卡名称和编号，方便竖着显示
 */
export function colList(text) {
  let str = text;
  // let numArr = str.match(/\d+(?:\.\d+)?/g);
  // let bNameArr = str.match(/[\u4e00-\u9fa5_a-zA-Z]+/g);
  // let num = numArr ? numArr[0] : "";
  // let bName = bNameArr ? bNameArr[0] : "";
  // return bName.split("").join("\n") + "\n" + num;

  if (text) {
    let strArr = str.split('');
    let newStr = '';
    strArr.forEach((item, index) => {
      if (/[\u4e00-\u9fa5_a-zA-Z]+/.test(item)) {
        newStr += item + '\n';
      } else if (strArr[index + 1] && /[\u4e00-\u9fa5_a-zA-Z]+/.test(strArr[index + 1])) {
        newStr += item + '\n';
      } else {
        newStr += item;
      }
    });
    return newStr;
  }
  return;
}

/**
 * [fileLengthFormat 格式化文件大小]
 * @param  {[int]} total [文件大小]
 * @param  {[int]} n     [total参数的原始单位如果为Byte，则n设为1，如果为kb，则n设为2，如果为mb，则n设为3，以此类推]
 * @return {[string]}       [带单位的文件大小的字符串]
 */
export function fileLengthFormat(total, n) {
  console.log(total, n);
  var format;
  var len = total / 1024.0;
  if (len > 1000) {
    console.log('*******', format);
    return fileLengthFormat(len, ++n);
  } else {
    switch (n) {
      case 1:
        format = len.toFixed(2) + 'KB';
        break;
      case 2:
        format = len.toFixed(2) + 'MB';
        break;
      case 3:
        format = len.toFixed(2) + 'GB';
        break;
      case 4:
        format = len.toFixed(2) + 'TB';
        break;
    }
    console.log('*******', format);
    return format;
  }
}

export function getFirstStampOfMon(stamp) {
  var date = new Date(stamp);
  date.setDate(1);
  var month = parseInt(date.getMonth() + 1);
  var day = date.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  let temp = date.getFullYear() + '-' + month + '-' + day;
  let res = new Date(temp).setHours(0, 0, 0);
  console.log(res);
  return res;
}
export function getLastStampOfMon(stamp) {
  var year = '';
  var date = new Date(stamp);
  var currentMonth = date.getMonth();
  var nextMonth = ++currentMonth;
  var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  var lastTime = new Date(nextMonthFirstDay);
  var month = parseInt(lastTime.getMonth() + 1);
  var day = lastTime.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  if (currentMonth === 12) {
    year = date.getFullYear() + 1;
  } else {
    year = date.getFullYear();
  }
  let temp = year + '-' + month + '-' + day;
  let res = new Date(temp).setHours(0, 0, 0);
  return res;
}

/**
 * 输入 value ， option ，输出 option 中对应的 label ,option 中的 value 和 label可以更改为自定义名字 筛选条件的日志推荐用getRefKeyValue更方便
 */
export function getOptionLabel(value, option, inputKey = 'value', resKey = 'label') {
  if (value == undefined || option == undefined) {
    return '';
  }
  let aim = '';
  aim = option.find((item) => {
    return item[inputKey] == value;
  });
  if (!aim) {
    return '';
  }
  return aim[resKey];
}

/**
 * 输入：通过ref获取的element组件；输出：组件名称和其中显示的值 （站点：xxx）
 */
export function getRefKeyValue(ref) {
  try {
    if (!ref) {
      console.log('【warn】getRefKeyValue 方法发现无入参');
      return '';
    }
    console.log(ref);
    // 判断是什么类型的组件 1：选项框 2.输入框 3.时间选择器
    let type = undefined;

    if (ref.selected) {
      type = 1;
    } else if (ref.type == 'text') {
      type = 2;
    } else if (ref.type == 'date' || ref.type == 'datetime') {
      type = 3;
    } else if (ref.type == 'daterange') {
      type = 4;
    }

    let str = '';

    if (type == 1) {
      str = (ref.name ? ref.name + '：' : '') + ref.selectedLabel;
      str += '; ';
    } else if (type == 2) {
      str = (ref.$attrs?.name ? ref.$attrs.name + '：' : '') + ref.value;
      str += '; ';
    } else if (type == 3) {
      str = (ref.name ? ref.name + '：' : '') + ref.displayValue;
      str += '; ';
    } else if (type == 4) {
      let value1 = '';
      let value2 = '';
      if (ref.value?.length > 0) {
        value1 = ref.value[0];
        value2 = ref.value[1];
      }
      str = (ref.name ? ref.name + '：' : '') + value1 + ' - ' + value2;
      str += '; ';
    } else {
      console.log('getRefKeyValue 未能解析出对应相应的组件，请检查方法是否有漏洞');
    }

    return str;
  } catch (error) {
    console.log('getRefKeyValue', error);
    return '';
  }
}
/**
 * 解析获取所有文件集合
 */
export const importAll = (r) => {
  let cache = {};
  r.keys().forEach((key) => (cache[key] = r(key)));
  console.log('批量获取文件：', cache);
  return cache;
};

/**
 * 用于获取dialogPages文件夹中每个子系统的index入口文件
 */
export const getSysIndexFile = (allFile) => {
  // 筛选子系统文件夹下的文件
  let fileWithIndex = {};
  for (const key in allFile) {
    // 第一级vue文件，且设置了name
    if (key.split('/').length - 1 === 2 && allFile[key].default.name) {
      fileWithIndex[key] = allFile[key];
    }
  }

  const componentsAll = {};
  for (const key in fileWithIndex) {
    const element = fileWithIndex[key].default;
    // 将vue文件的name值注册为组件名称
    componentsAll[element.name] = element;
  }
  console.log('成功注册的子系统入口文件列表：', componentsAll);
  return componentsAll;
};
